<?php
/**
 * ListMallProduct.php class file.
 * @author wudg <544038230@qq.com>
 * @date 2020/11/17- 10:43 上午
 */

namespace common\models\es\dataProvider\tbMallProductsSkus;

use Yii;

class ListMallProductSkus extends Query
{

    public function getData()
    {
        $params = [
            'index' => $this->getIndexName(),
            'body' => $this->getBody()
        ];
//        print_r($this->query);
//        print_r(json_encode($params['body'])); exit;
        $esResult = Yii::$app->elasticsearch->search($params);
        return $esResult['aggregations']['goodsIdField']['buckets'] ?? [];
    }


    /**
     * 拼装请求体
     * @return array
     */
    protected function getBody()
    {
        $return = [
            'track_total_hits' => true,
            '_source' => $this->fields,
            'size' => 10000,
            'from' => 0,
            'query' => $this->getQueryBody(),
            'sort' => $this->sort,
            'aggs' => [
                'goodsIdField' => [
                    'terms' => [
                        'field' => 'goods_id',
                        'size' => 500
                    ]
                ]
            ]
        ];

//        if (isset($this->query['goods_name']) && $this->query['goods_name']) {
//            $return['highlight'] = ['fields' => ['goods_name' => (object)[]]];
//        }
        return $return;
    }

    protected function getQueryBody()
    {
        return [
            'bool' => [
                'filter' => $this->getFilter()
            ],
        ];
    }

    /**
     * 拼装过滤条件
     * @return array
     */
    protected function getFilter(): array
    {

        $filter = [];
        //用户ID
        if (isset($this->query['uid']) && !empty($this->query['uid'])) {
            $filter[] = [
                ['term' => ['uid' => $this->query['uid']]]
            ];
        }

        //店铺id
        if (isset($this->query['mall_id']) && !empty($this->query['mall_id'])) {
            $filter[] = [
                ['terms' => ['mall_id' => $this->query['mall_id']]]
            ];
        }
        //根据违禁词搜索
        if (isset($this->query['words']) && !empty($this->query['words'])) {
            $words = [];
            foreach ($this->query['words'] as $k => $v) {
                if($v=='?'||$v=='\\'){
                    $v = "\\".$v;
                }
                $goods_info =
                    array(
                        'wildcard' => array(
                            'spec_name' => '*' . $v . '*'
                        )
                    );
                $words[] = $goods_info;
            }

            $filter[] = [
                'bool' => [
                    'should' => $words
                ]
            ];
        }
        return $filter;
    }


}
